﻿using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YanZhiwei.DotNet2.Utilities.Common;
namespace YanZhiwei.DotNet2.Utilities.AspNet
{
    /// <summary>
    ///  GridView 帮助类
    /// </summary>
    public static class GridViewHelper
    {
        #region  将GridView导出到EXCEL
        /// <summary>
        /// 将GridView导出到EXCEL
        /// </summary>
        /// <param name="girdview">GridView</param>
        /// <param name="fileName">导出到的文件名称</param>
        public static void ToExcel(this GridView girdview, string fileName)
        {
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString());
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            girdview.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            girdview.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
        }
        #endregion
        #region 从GridView的数据生成DataTable
        /// <summary>
        /// 从GridView的数据生成DataTable
        /// </summary>
        /// <param name="gv">GridView对象</param>
        public static DataTable GridView2DataTable(GridView gv)
        {
            DataTable _table = new DataTable();
            int _rowIndex = 0;
            List<string> cols = new List<string>();
            if (!gv.ShowHeader && gv.Columns.Count == 0)
            {
                return _table;
            }
            GridViewRow _headerRow = gv.HeaderRow;
            int _columnCount = _headerRow.Cells.Count;
            for (int i = 0; i < _columnCount; i++)
            {
                string text = GetCellText(_headerRow.Cells[i]);
                cols.Add(text);
            }
            foreach (GridViewRow r in gv.Rows)
            {
                if (r.RowType == DataControlRowType.DataRow)
                {
                    DataRow _row = _table.NewRow();
                    int j = 0;
                    for (int i = 0; i < _columnCount; i++)
                    {
                        string text = GetCellText(r.Cells[i]);
                        if (!string.IsNullOrEmpty(text))
                        {
                            if (_rowIndex == 0)
                            {
                                string columnName = cols[i];
                                if (string.IsNullOrEmpty(columnName))
                                {
                                    continue;
                                }
                                if (_table.Columns.Contains(columnName))
                                {
                                    continue;
                                }
                                DataColumn dc = _table.Columns.Add();
                                dc.ColumnName = columnName;
                                dc.DataType = typeof(string);
                            }
                            _row[j] = text;
                            j++;
                        }
                    }
                    _rowIndex++;
                    _table.Rows.Add(_row);
                }
            }
            return _table;
        }
        #endregion
        #region 获取单元格内容
        /// <summary>
        /// 获取单元格内容
        /// </summary>
        /// <param name="cell">TableCell</param>
        /// <returns>内容</returns>
        private static string GetCellText(TableCell cell)
        {
            string text = cell.Text;
            if (!string.IsNullOrEmpty(text))
            {
                return text;
            }
            foreach (Control control in cell.Controls)
            {
                if (control != null && control is IButtonControl)
                {
                    IButtonControl btn = control as IButtonControl;
                    text = btn.Text.Replace("\r\n", "").Trim();
                    break;
                }
                if (control != null && control is ITextControl)
                {
                    LiteralControl lc = control as LiteralControl;
                    if (lc != null)
                    {
                        continue;
                    }
                    ITextControl l = control as ITextControl;
                    text = l.Text.Replace("\r\n", "").Trim();
                    break;
                }
            }
            return text;
        }
        #endregion
        #region 设置单元格内容
        /// <summary>
        /// 设置单元格内容
        /// </summary>
        /// <param name="cell">TableCell</param>
        /// <param name="maxLen">最大长度</param>
        private static void SetCellText(TableCell cell, int maxLen)
        {
            string text = cell.Text;
            if (!string.IsNullOrEmpty(text))
            {
                cell.Text = StringHelper.Substring(text, maxLen);
            }
            foreach (Control control in cell.Controls)
            {
                if (control != null && control is IButtonControl)
                {
                    IButtonControl btn = control as IButtonControl;
                    text = btn.Text.Replace("\r\n", "").Trim();
                    btn.Text = StringHelper.Substring(text, maxLen);
                    break;
                }
                if (control != null && control is ITextControl)
                {
                    LiteralControl _lc = control as LiteralControl;
                    if (_lc != null)
                    {
                        continue;
                    }
                    ITextControl _l = control as ITextControl;
                    text = _l.Text.Replace("\r\n", "").Trim();
                    if (_l is DataBoundLiteralControl)
                    {
                        cell.Text = StringHelper.Substring(text, maxLen);
                        break;
                    }
                    else
                    {
                        _l.Text = StringHelper.Substring(text, maxLen);
                        break;
                    }
                }
            }
        }
        #endregion

        //    static readonly string sqlconnectionString = @"Server=YANZHIWEI-PC\SQLEXPRESS;DataBase=Test;uid=sa;pwd=sasa";
        //    MSSQLToolV2 SqlHelper = new MSSQLToolV2(sqlconnectionString);
        //    protected void Page_Load(object sender, EventArgs e)
        //    {
        //        if (!Page.IsPostBack)
        //        {
        //            ViewState["OrderType"] = "ASC";
        //            ViewState["SortColumn"] = "Date";
        //            BindLogToView();
        //        }
        //    }
        //    private void BindLogToView()
        //    {
        //        string _sql = "select  top 10 * from [Log]";
        //        DataTable _dtResource = SqlHelper.ExecuteDataTable(_sql, null);
        //        DataView _view = _dtResource.DefaultView;
        //        string _sort = (string)ViewState["SortColumn"] + " " + (string)ViewState["OrderType"];
        //        _view.Sort = _sort;
        //        this.GridView1.DataSource = _view;
        //        this.GridView1.DataBind();
        //    }
        //    /// <summary>
        //    /// 修改
        //    /// </summary>
        //    /// <param name="sender"></param>
        //    /// <param name="e"></param>
        //    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        //    {

        //        try
        //        {
        //            string _id = GridView1.Rows[e.RowIndex].Cells[3].Text;
        //            if (!string.IsNullOrEmpty(_id))
        //            {
        //                SqlParameter[] _parameters = new SqlParameter[1];
        //                _parameters[0] = new SqlParameter("@ID", _id);
        //                string _sql = "delete [Log] where ID=@ID";
        //                if (SqlHelper.ExecuteNonQuery(_sql, _parameters) > 0)
        //                {
        //                    BuilderScriptAlert("删除成功");
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            BuilderScriptAlert(string.Format("删除失败,原因:{0}", ex.Message.Trim()));
        //        }
        //        finally
        //        {
        //            BindLogToView();
        //        }
        //    }

        //    private void BuilderScriptAlert(string message)
        //    {
        //        if (!string.IsNullOrEmpty(message))
        //        {
        //            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('" + message + "')", true);
        //        }
        //    }
        //    /// <summary>
        //    /// 进去编辑
        //    /// </summary>
        //    /// <param name="sender"></param>
        //    /// <param name="e"></param>
        //    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        //    {
        //        GridView1.EditIndex = e.NewEditIndex;
        //        BindLogToView();
        //    }
        //    /// <summary>
        //    /// 取消编辑
        //    /// </summary>
        //    /// <param name="sender"></param>
        //    /// <param name="e"></param>
        //    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        //    {
        //        GridView1.EditIndex = -1;
        //        BindLogToView();
        //    }
        //    /// <summary>
        //    /// 更新
        //    /// </summary>
        //    /// <param name="sender"></param>
        //    /// <param name="e"></param>
        //    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        //    {

        //        string _id = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim();
        //        try
        //        {
        //            if (!string.IsNullOrEmpty(_id))
        //            {
        //                string _updateTime = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString().Trim();
        //                SqlParameter[] _parameters = new SqlParameter[2];
        //                _parameters[0] = new SqlParameter("@Date", _updateTime);
        //                _parameters[1] = new SqlParameter("@ID", _id);
        //                string _sql = "Update [Log] set Date=@Date where ID=@ID";
        //                if (SqlHelper.ExecuteNonQuery(_sql, _parameters) > 0)
        //                {
        //                    BuilderScriptAlert(string.Format("修改ID：{0}时间为{1}成功！", _id, DateTime.Parse(_updateTime)));
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            BuilderScriptAlert(string.Format("修改ID:{0}失败,原因：{1}", _id, ex.Message.Trim()));
        //        }
        //        finally
        //        {
        //            GridView1.EditIndex = -1;
        //            BindLogToView();
        //        }
        //    }
        //    /// <summary>
        //    /// 排序
        //    /// Remarks:1==>SortExpression="ID"
        //    /// 2==》AllowSorting="True"
        //    /// </summary>
        //    /// <param name="sender"></param>
        //    /// <param name="e"></param>
        //    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        //    {
        //        string _page = e.SortExpression;
        //        if (!string.IsNullOrEmpty(_page))
        //        {
        //            if (ViewState["SortColumn"].ToString() == _page)
        //            {
        //                if (ViewState["OrderType"].ToString() == "ASC")
        //                    ViewState["OrderType"] = "Desc";
        //                else
        //                    ViewState["OrderType"] = "ASC";
        //            }
        //            else
        //            {
        //                ViewState["SortColumn"] = e.SortExpression;
        //            }
        //            BindLogToView();
        //        }
        //    }
        //}
    }
}
